package com.rockcent.job.task;

import com.rockcent.common.domain.enumclass.Whether;
import com.rockcent.common.utils.DateFormatUtils;
import com.rockcent.common.utils.DateUtils;
import com.rockcent.mall.lib.domain.Merchant;
import com.rockcent.mall.lib.domain.MallFinancialSettings;
import com.rockcent.mall.lib.repository.MallRepository;
import com.rockcent.mall.lib.repository.MallFinancialSettingsRepository;
import com.rockcent.service.MerchantServiceFeeSrv;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.List;

/**
 * Created by hone on 17-4-1.
 */
@Component
public class MerchantFeeToMallTask {

    final Logger log = LoggerFactory.getLogger(MerchantFeeToMallTask.class);

    @Autowired
    private MallFinancialSettingsRepository merchantFinancialSettingsRepository;
    @Autowired
    private MallRepository mallRepository;
    @Autowired
    private MerchantServiceFeeSrv merchantServiceFeeSrv;

    /**
     * 扣减商户基础服务费
     * 0 0 0 * * ? 每天凌晨执行任务
     */
    @Scheduled(cron = "${job.chargeMerchantServiceFee.cron}")
    @Transactional(propagation = Propagation.REQUIRED)
    public void charge() {
//        log.info("======================>merchantFeeToMallTask start");
        //获取平台财务设置列表
        List<MallFinancialSettings> settingsList = merchantFinancialSettingsRepository.findByIsDelete(Whether.NO);
        if (settingsList != null && settingsList.size() > 0) {
            for (MallFinancialSettings set : settingsList) {
                if (set.getMallId() != null && set.getBaseServiceFee() != null) {
                    List<Merchant> merchants = mallRepository.findMerchantsByMallId(set.getMallId());
                    if (merchants != null && merchants.size() > 0) {
                        handler(merchants, set.getBaseServiceFee());
                    }
                }
            }
        }
//        log.info("======================>merchantFeeToMallTask end");
    }

    /**
     * 处理商户列表
     *
     * @param merchants
     */
    private void handler(List<Merchant> merchants, BigDecimal baseServiceFee) {
        for (Merchant merchant : merchants) {
            if (null != merchant) {
                if (checkChargeDate(merchant.getSettlementDate())) {
                    //调用扣费接口
                    merchantServiceFeeSrv.deductions(merchant.getMallId(), merchant.getId(), DateUtils.getCurrentTime(DateFormatUtils.DATE_FORMAT1), baseServiceFee);
//                    log.info("======================>扣减的商户ID为:{},服务费为:{}", merchant.getId(), baseServiceFee);
                }
            } else {
//                log.info("======================>merchant:{}", merchant);

            }

        }
    }

    /**
     * 检查是否符合扣费日期
     *
     * @return
     */
    private boolean checkChargeDate(String chargeDate) {
        if (StringUtils.isEmpty(chargeDate)) {
            return false;
        }
        String currentDay = getDay();
        if (chargeDate.equals(currentDay)) {
            return true;
        }
        String currentMonthLastDay = DateUtils.getCurrentMonthLastDay();
        int dateInt = Integer.parseInt(chargeDate);
        int lastDayInt = DateUtils.getCurrentDay(currentMonthLastDay);
        if (dateInt > lastDayInt) {
            if (lastDayInt == Integer.parseInt(currentDay)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 获取当前几号
     *
     * @return
     * @throws Exception
     */
    private String getDay() {
        //获取当前日期
        String currentDate = DateUtils.getCurrentTime(DateFormatUtils.DATE_FORMAT1);
        //找出几号
        String currentDay = currentDate.substring(8, currentDate.length());
        return currentDay;
    }
}
